<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 微信交互类
 */ 
namespace app\home\controller;
use app\home\logic\UsersLogic;
class Weixin extends Base {
    public $client;
    public $wechat_config;
    public function _initialize(){
        parent::_initialize();
        //获取微信配置信息
        $this->wechat_config = M('wx_user')->find();        
        $options = array(
 			'token'=>$this->wechat_config['w_token'], //填写你设定的key
 			'encodingaeskey'=>$this->wechat_config['aeskey'], //填写加密用的EncodingAESKey
 			'appid'=>$this->wechat_config['appid'], //填写高级调用功能的app id
 			'appsecret'=>$this->wechat_config['appsecret'], //填写高级调用功能的密钥
        		);

    }

    public function oauth(){

    }
    
    public function index(){
        if($this->wechat_config['wait_access'] == 0)        
            exit($_GET["echostr"]);
        else        
            $this->responseMsg();
    }    
    
    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
	 if (empty($postStr))                 	
        	exit("");
                
                file_put_contents("./public/log/Wxtest.txt",$postStr,FILE_APPEND);//抓取微信异步回调数据
                
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                
                /*
                 * 关注公众号事件
                 */
                if($postObj->MsgType == 'event' && $postObj->Event == 'subscribe')
                {  
                    //获取用户信息
                    $accesstoken = getWx_access_token();
                    $user_info = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accesstoken&openid=$fromUsername&lang=zh_CN");
                    $wxuser = json_decode($user_info,true);
                    
                    $wxuser['first_leader'] = substr($postObj->EventKey,8);//推荐人
                    $wxuser['oauth']= 'weixin';//账户来源
                    $wxuser['is_follow'] = 1; 

                    //第三方登陆
                    $logic = new UsersLogic();
                    $data = $logic->thirdLogin($wxuser);

                	$wx_img = M('wx_img')->where('is_auto',1)->find();
                	if(empty($wx_img)){
                		$wx_img = M('wx_img')->limit(1)->order('id DESC')->find();//若未设置，找最新一个作为关注推送
                	}
                    $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <ArticleCount><![CDATA[%s]]></ArticleCount>
                            <Articles>
                                <item>
                                    <Title><![CDATA[%s]]></Title> 
                                    <Description><![CDATA[%s]]></Description>
                                    <PicUrl><![CDATA[%s]]></PicUrl>
                                    <Url><![CDATA[%s]]></Url>
                                </item>                               
                            </Articles>
                            </xml>";                                        
                    $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,'news','1',$wx_img['title'],$wx_img['desc']
                            , $wx_img['pic'], $wx_img['url']);
                    exit($resultStr);                   
                    $keyword = trim($postObj->EventKey);
                }
                
                
                /*
                 * 取消关注公众号事件
                 */
                if($postObj->MsgType == 'event' && $postObj->Event == 'unsubscribe')
                {   
                	file_put_contents("./public/log/sql.txt","\n\r取消关注--".$fromUsername."--".date("Y-m-d H:i:s",time()),FILE_APPEND);                	
                	M('users')->where(array('openid'=>"$fromUsername"))->save(array('is_follow'=>0));
                	$sql = M('users')->getLastSql();
                }	
                
                
                 /*
                 * 扫码事件
                 */
                if($postObj->MsgType == 'event' && $postObj->Event == 'SCAN')
                {
                	$textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";                    
                    $contentStr = '亲，您已关注封坛天下，祝您生活愉快！';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
                    exit($resultStr);            
                }
                //点击菜单拉取消息时的事件推送 
                /*
                 * 1、click：点击推事件
                 * 用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南）
                 * 并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
                 */
                if($postObj->MsgType == 'event' && $postObj->Event == 'CLICK')
                {
                    $keyword = trim($postObj->EventKey);
                }
                
                if($postObj->MsgType == 'event' && $postObj->Event == 'LOCATION')
                {
                    exit("success");
                }
                
                if(empty($keyword))
                    exit("success");
                
                // 图文回复
                $wx_img_allkeywords = M('wx_img')->select();
                foreach ($wx_img_allkeywords as $key=>$value){
                    if(strpos($keyword,$value['keyword']) !== false){
                        $wx_img = $value;
                        break;
                    }
                }
                if($wx_img)
                {
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount><![CDATA[%s]]></ArticleCount>
                                <Articles>
                                    <item>
                                        <Title><![CDATA[%s]]></Title> 
                                        <Description><![CDATA[%s]]></Description>
                                        <PicUrl><![CDATA[%s]]></PicUrl>
                                        <Url><![CDATA[%s]]></Url>
                                    </item>                      
                                </Articles>
                                </xml>";                                        
                    $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,'news','1',$wx_img['title'],$wx_img['desc']
                               , $wx_img['pic'], $wx_img['url']);
                    exit($resultStr);                   
                }
                
                
                // 文本回复
                $wx_text_allkeywords = M('wx_text')->select();
                foreach ($wx_text_allkeywords as $key=>$value){
                    if(strpos($keyword,$value['keyword']) !== false){
                        $wx_text = $value;
                        break;
                    }
                }
                if($wx_text)
                {
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";                    
                    $contentStr = $wx_text['text'];
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
                    exit($resultStr);                   
                }
                
                
                // 其他文本回复                
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";                    
                    $contentStr = '中国原产地酒C2F个性化定制平台欢迎您！';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
                    exit($resultStr);                   
      
    }    
}